import type {Ref} from 'vue';
import {computed, ref} from "vue";
import {defineStore} from "pinia";
import type {dateInfoInterface} from '@/assets/ts/Interface'
import {delRestful, getRestful, postRestful} from "@/assets/ts/common";


//{"id":"172122058591681666","name":"东","isLunar":1,"lunarDate":"1999/12/25","isTop":1}
const objectArr: object[] = [];


export const useCommonStore = defineStore("commonStore", () => {

        //state
        const theme = ref("light");
        const title = ref({
            name: "Days Matter",
            hasBack: true
        });
        const openId: Ref<string> = ref('');
        const userData = ref({
            id: "",
            avatarUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
            city: "未设置",
            email: '',
            country: "未设置",
            gender: 0, // 0: 未知, 1: 男, 2: 女
            language: "未设置",
            nickName: "用户昵称",
            province: "未设置"
        });

        const dateInfoList = ref(objectArr);
        //getter
        const isLightTheme = computed(() => theme.value === "light");

        //action
        function setTheme(themeParam: string) {
            theme.value = themeParam || theme.value;
            document.documentElement.setAttribute("theme", theme.value);
        }

        /**
         * 设置日期
         * @param dateInfo
         */
        function setDateInfo(dateInfo: dateInfoInterface) {
            console.log(dateInfo)
            if (!openId.value) {
                needLogin()
                return;
            }
            dateInfo.weight = dateInfoList.value.length + 1


            dateInfo.openId = openId.value
            let url = '/api/dateList'
            postRestful(url, dateInfo, false).then((res:any) => {
                if (res && res.id) {
                    getDateList()
                    uni.switchTab({url: '/pages/dateList/index'})
                } else {
                    console.error('保存失败', res)
                    uni.showToast({
                        title: "保存失败, "+(res && res.message ? JSON.stringify(res.message) : ''),
                        icon: 'none'
                    })
                }
            }).catch(err => {
                console.error('保存失败', err)
                uni.showToast({
                    title: "保存失败, " + err ? JSON.stringify(err.message) : '',
                    icon: 'none'
                })
            })
        }

        function logout() {
            openId.value = ''
        }

        function deleteDate(id: string) {
            let url = `/api/dateList/${id}`
            delRestful(url, false).then(getDateList)
        }

        function getId() {
            return new Date().getTime() + (100000 * Math.random()).toFixed(0);
        }

        function setOpenId(id: string) {
            if (!id) return;
            openId.value = id
            setUserInfo(userData.value)
        }

        function needLogin() {
            uni.showToast({
                title: "请先登录",
            })
            uni.navigateTo({
                url: '/pages/login/index'
            });
        }

        // 服务器请求
        //  查询
        async function getDateList() {
            dateInfoList.value = []
            if (!openId.value) {
                needLogin()
                return;
            }
            let url = `/api/dateList/byOpenId?openId=${openId.value}`

            await getRestful(url, false).then(res => {
                // @ts-ignore
                if (!res || !Array.isArray(res)) return;
                dateInfoList.value = res.sort((a, b) => {
                    return b.weight - a.weight
                })
                console.log(dateInfoList.value)
            })
        }


        //查询用户详情
        function getUserInfo() {
            if (!openId.value) {
                needLogin()
                return;
            }
            let url = `api/user/by-openid?openId=${openId.value}`
            getRestful(url, false).then(res => {
                // @ts-ignore
                if (res.openId) userData.value = res;

            })
        }

        function setUserInfo(userInfo: any) {
            if (!openId.value) {
                needLogin()
                return;
            }
            userData.value = userInfo
            userInfo.openId = openId.value

            let param = {
                ...userInfo
            }
            let url = `api/user/saveOrUpdate`
            postRestful(url, param, false).then(() => {
                console.log('保存成功')
            })


        }

        return {
            openId, setOpenId,
            userData,
            logout,
            dateInfoList,
            theme,
            isLightTheme,
            setDateInfo,
            setTheme,
            deleteDate,
            title,
            setUserInfo,
            getUserInfo,
            getDateList
        };
    },
    {
        persist: {
            storage: {
                getItem(key) {
                    return uni.getStorageSync(key)
                },
                setItem(key, value) {
                    uni.setStorageSync(key, value)
                },
            }
        }
    }
);




